<?php
declare (strict_types = 1);

namespace app\admin\service;

use app\admin\model\auth\AdminLogModel;
use app\admin\model\common\ConfigModel;
use think\facade\Cache;
use think\Model;
use think\facade\Db;
use think\Request;

class BaseService
{
    /**
     * 获取配置项
     * @param string $type 配置类型
     * @return array
     */
    protected function getConfByType($type) {
        try {
            $res = ConfigModel::where('block',$type)->select()->toArray();
            $Config = [];
            foreach($res as $v){
                $Config[$v['key']] = $v['value'];
            }
            return $Config;
        } catch (\Exception $e) {
            return [];
        }
    }
    /**
     * 校验参数唯一性和必填
     * @param $model 模型
     * @param $param 前端传参
     * @param $uniqueFields 唯一性字段数组 ['username']
     * @param $requiredFields 必填字段数组 ['role','password']
     * @return array|true
     */
    protected function checkParams($model, $param, $uniqueFields = [], $requiredFields = [], $customMsg = [])
    {
        foreach ($uniqueFields as $field) {
            if (isset($param[$field]) && $this->checkUnique($model, $field, $param[$field], $param['id'] ?? null)) {
                $msg = $customMsg[$field.'_unique'] ?? ($field . '已存在');
                return ['code'=>500, 'msg'=>$msg];
            }
        }
        // 必填校验
        foreach ($requiredFields as $field) {
            if (empty($param[$field])) {
                $msg = $customMsg[$field.'_required'] ?? ($field . '不能为空');
                return ['code'=>500, 'msg'=>$msg];
            }
        }
        return true;
    }
    /**
     * 检查字段值的唯一性
     * @param Model $model  模型实例
     * @param string $field 字段名
     * @param mixed $value 字段值
     * @param int|null $id 排除的ID（编辑时使用）
     * @return bool
     */
    protected function checkUnique($model, $field, $value, $id = null)
    {
        $where = [[$field, '=', $value]];
        if ($id) {
            $where[] = ['id', '<>', $id];
        }
        return $model->where($where)->count() > 0;
    }
     /**
     * 通用分页查询封装
     * @param Model $model          模型实例
     * @param array $param          请求参数
     * @param array $selectFields   需要查询的字段, 默认所有
     * @param array $searchFields   需要进行模糊搜索的字段
     * @param array $exactFields    需要进行精确匹配的字段
     * @param string $dateField     进行日期范围查询的字段
     * @param string $order         ID排序方式 ('desc' 或 'asc')
     * @return \think\Paginator
     */
    protected function paginateWithSearch(
        Model $model,
        array $param,
        array $selectFields = [],
        array $searchFields = [],
        array $exactFields = [],
        string $dateField = 'created_at',
        string $order = 'desc') 
    {
        $current = isset($param['current']) ? intval($param['current']) : 1;
        $size = isset($param['size']) ? intval($param['size']) : 10;
        $where = [];
        if (!empty($param['search']) && $searchFields) {
            $where[] = function($query) use ($param, $searchFields) {
                foreach ($searchFields as $field) {
                    $query->whereOr($field, 'like', '%' . $param['search'] . '%');
                }
            };
        }
        foreach ($exactFields as $field) {
            if (isset($param[$field]) && $param[$field] !== '') {
                $where[] = [$field, '=', $param[$field]];
            }
        }
        if (!empty($param['startTime']) && !empty($param['endTime'])) {
            $start = strtotime($param['startTime']);
            $end = strtotime($param['endTime']) + 86399;
            $where[] = [$dateField, 'between', [$start, $end]];
        } elseif (!empty($param['startTime'])) {
            $start = strtotime($param['startTime']);
            $where[] = [$dateField, '>=', $start];
        } elseif (!empty($param['endTime'])) {
            $end = strtotime($param['endTime']) + 86399;
            $where[] = [$dateField, '<=', $end];
        }

        // 执行查询
        $paginator = $model->field($selectFields)->where($where)->order('id', $order)->paginate([
            'list_rows' => $size,
            'page'      => $current,
            'query'     => $param,
        ]);
        $result = $paginator->toArray();
        unset($result['has_more']);
        return $result;
    }
    /**
     * 写入后台操作日志
     * @param string $title 日志标题
     * @param int $type 日志类型 1新增 2修改 3删除 4登录 5其他
     * @param string $id 管理员ID
     * @param string $username 管理员用户名
     * @return void
     */
    protected function writeLog($title,$type)
    {
        $LogModel = new AdminLogModel();
        $token = getJWT(getHeaderToken());
        $id = $token['id'];
        $username = $token['username'];
        $LogModel->addLog($title,$type,$id,$username);
    }
}